package com.dingpeikeji.quickdeer.modules.quartz;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alipay.api.RefundFastpayByPlatformNopwdApi;
import com.alipay.config.AlipayConfig;
import com.alipay.model.RefundFastpayByPlatformNopwdReq;
import com.alipay.util.AlipaySubmit;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrdersOut;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersOutService;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.payinfo.entity.TPayinfo;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.modules.realsche.service.FRealscheService;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ShareRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.ShareProductService;
import com.dingpeikeji.quickdeer.modules.sms.entity.Sms;
import com.dingpeikeji.quickdeer.modules.sms.service.SmsApi;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.google.common.collect.Lists;
import com.tencent.WXPay;
import com.tencent.common.Configure;
import com.tencent.protocol.refund_protocol.RefundReqData;

public class ShareProductJob implements Job{
	
	@Autowired
	private ShareProductService shareProductService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private FRealscheService fRealscheService;
	@Autowired
	private TOrdersOutService tOrdersOutService;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void execute(JobExecutionContext context ) throws JobExecutionException {
		//每分钟执行一次,当前时间大于shareproduct表中的enddate,产品已经过期,修改delflag为1
		System.out.println("定时任务启动......................\n");
		List<ShareRentproduct> list=shareProductService.selectDelFlag();
		if(list!=null&&list.size()>0){
			shareProductService.updateDelFlag();
			for(int i=0;i<list.size();i++){
				List<TOrders> orderlist=tOrdersService.getOrderByShareId(list.get(i).getSid());
				if(orderlist!=null&&orderlist.size()>0){
					for(int j=0;j<orderlist.size();j++){
						if(orderlist.get(j).getOrderstatus().equals("0")){
							try{
								String t=backMoney(orderlist.get(j));
								if(t==null){
									System.out.println("--------订单号："+orderlist.get(j).getOrderid() +" 退款成功--------\n");
								}else{
									System.err.println("--------订单号："+orderlist.get(j).getOrderid() +" 退款失败："+t+"--------\n");
								}
							}catch (Exception e) {
								System.err.println("--------订单号："+orderlist.get(j).getOrderid() +" 退款异常！--------\n");
								continue;
							}
						}
					}
				}
			}
		}
	}
	
	public String backMoney(TOrders orders) {
		TOrders torders = fRealscheService.getOrders(orders.getOrderid());
		// ==========>>数据校验
		List<String> messages = Lists.newArrayList(); // 消息
		boolean sendSms = false; // 是否发送短信
		if(messages.isEmpty()) {
			TPayinfo payinfo = torders.getPayinfo();
			if(payinfo!=null && payinfo.getDiscountid() != null){
				Map<String,Object> result = fRealscheService.proCmptReturn(orders);
				Integer returnflag = (Integer) result.get("returnflag");
				if(returnflag!=null&&returnflag==0){
					String payway = torders.getPayway();
					//批次号，必填，格式：当天日期[8位]+序列号[3至24位]，如：201603081000001
					String batch_no = new SimpleDateFormat("yyyyMMdd").format(new Date())+UUID.randomUUID().toString().replace("-", "").substring(0, 16);
					//退款笔数，必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
					String batch_num = "1";
					Double money = (Double) result.get("returnmoney");
					//退款详细数据，必填，格式（支付宝交易号^退款金额^备注），多笔请用#隔开
					String detail_data = payinfo.getFlowno() // 流水号就是支付宝单号
							+"^"+money+"^"
							+torders.getPurchasenum()+","+torders.getChildnum(); // 退款数量
					if(payway.equals(TOrders.PAY_WAY_ALIPAY)){ // 支付宝支付
						String refund_date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
						try {
							RefundFastpayByPlatformNopwdReq req = new RefundFastpayByPlatformNopwdReq(batch_no, refund_date, batch_num, detail_data);
							//new RefundFastpayByPlatformNopwdApi().execute(req, request, response);
							execute(req);
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(Integer.parseInt(torders.getChildnum()==null?"0":torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
							messages.add("支付宝退票请求成功！");
							sendSms = true;
						} catch (Exception e) {
							messages.add("请求退款异常！");
							return "请求退款异常！";
						}
					}
					if(payway.equals(TOrders.PAY_WAY_WXPAY)){ // 微信支付
						String out_trade_no = "";
						for(int i=0;i<32-orders.getOrderid().length();i++){ // 补齐32位字符串
							out_trade_no+="0";
						}
						int moneyint = (int)(money*100);
						out_trade_no+=torders.getOrderid();
						RefundReqData refundReqData = new RefundReqData(""//payinfo.getFlowno()
								, out_trade_no, ""
								, batch_no
								, (int)(Double.valueOf(torders.getDueamount())*100)
								, moneyint
								, Configure.getMchid()
								, "CNY");
						try {
							if(moneyint != 0){
								String responseString = WXPay.requestRefundService(refundReqData);
								logger.debug("微信退款返回信息：{}",responseString);
							}
							// 保存退款信息
							TOrdersOut orderOut = new TOrdersOut();
							orderOut.setOrderid(Integer.parseInt(torders.getOrderid()));
							orderOut.setBatchNo(batch_no);
							orderOut.setOutnum(Integer.parseInt(torders.getPurchasenum()));
							orderOut.setRtnmoney(money);
							orderOut.setOutchildnum(Integer.parseInt(torders.getChildnum()==null?"0":torders.getChildnum()));
							orderOut.setNotifyed(TOrdersOut.NOTIFED_NO);
							orderOut.setOutuserid(UserUtils.getUser().getId());
							orderOut.setRtnstatus(TOrdersOut.RTN_STATUS_FAIL);
							tOrdersOutService.save(orderOut);
							fRealscheService.proConfirmRtn(batch_no);
							if(moneyint == 0){
								messages.add("收取手续费后，可退费用为0元！");
							} else {
								messages.add("微信退票请求成功！");
							}
							sendSms = true;
						} catch (Exception e) {
							logger.debug("微信退票异常信息", e);
							messages.add("请求退款异常！");
							return "请求退款异常！";
						}
					}
				} else {
					messages.add((String) result.get("returnmsg"));
				}
			} else {
				messages.add("订单暂未生效！");
				return "订单暂未生效！";
			}
		}
		
		// 订车人申请退单成功后，收到平台短信
		if(sendSms){
			Sms sms = new Sms();
			sms.setMobile(torders.getPayertel());
			sms.setContent("【霞客约车】您购买的"+torders.getOrdername()+"订单（"+torders.getOrderid()+"）已取消，我们将根据预订规则将相应款项在3个工作日内返回您的支付账户。");
			try {
				SmsApi.sendSms(sms);
				return null;
			} catch (Exception e) {
			}
		}
		return messages.get(0);
	}
	
	public void execute(RefundFastpayByPlatformNopwdReq req) throws Exception {
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", AlipayConfig.refund_fastpay_by_platform_nopwd_service);
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("notify_url", AlipayConfig.refund_notify_url);
		sParaTemp.put("batch_no", req.getBatch_no());
		sParaTemp.put("refund_date", req.getRefund_date());
		sParaTemp.put("batch_num", req.getBatch_num());
		sParaTemp.put("detail_data", req.getDetail_data());
		
		//建立请求
		String sHtmlText = AlipaySubmit.buildRequest("", "", sParaTemp);
//		response.setContentType("text/html");
//		response.getWriter().print(sHtmlText);
	}
	
	
}
